package com.itheima.train.manager.order;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class CuratorFrameworkConfiguration {

    @Autowired
    private Environment environment ;

    @Bean
    public CuratorFramework curatorFramework() {

        // 第一个参数：两次连接的等待时间，第二个参数：表示的是最大的重试次数
        ExponentialBackoffRetry exponentialBackoffRetry = new ExponentialBackoffRetry(1000 , 3) ;
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(environment.getProperty("zk.cluster.nodes"))
                .retryPolicy(exponentialBackoffRetry)
                .namespace("itheima-train-znode")
                .sessionTimeoutMs(5000)
                .build();
        curatorFramework.start();

        return curatorFramework ;

    }

    @Bean
    public InterProcessMutex interProcessMutex(CuratorFramework curatorFramework) {
        return new InterProcessMutex(curatorFramework , "/lock-znode") ;
    }

}
